<?php

namespace app\common\repositories\system\upload;

use app\common\repositories\BaseRepository;
use app\common\dao\system\upload\SystemUploadFileDao;
use app\common\services\UploadService;

class SystemUploadFileRepository extends BaseRepository
{
    // 存储类型
    const STORAGE_TYPE = [
        'local' => '本地',
        'aliyun' => '阿里云OSS',
        'qiniu' => '七牛云存储',
        'qcloud' => '腾讯云COS'
    ];

    public function __construct(SystemUploadFileDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @param array $where
     * @param $page
     * @param $limit
     * @return array
     */
    public function getList(int $propertyId, array $where = [], $filed = '*', $page = 1, $limit = 15,)
    {
        $query = $this->dao->search($propertyId, $where);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->field($filed)
            ->order('id', 'desc')
            ->select();
        return compact('list', 'count');
    }


    /**
     * 删除上传文件
     *
     * @param $uploadFileInfo
     * @return bool
     */
    public function delUploadFile($uploadFileInfo)
    {
        try {
            $storageType = $uploadFileInfo['storage_type'] ?: 'local';
            $uploadPath = $uploadFileInfo['upload_path'];
            if ($storageType == 'local') {
                $uploadPath = app()->getRootPath() . 'public/' . $uploadPath;
            }
            $uploadService = UploadService::init($uploadFileInfo['property_id']);
            $uploadService->setDriver($storageType);
            $res = $uploadService->deleteFile($uploadPath);
            if ($res) {
                $this->dao->delete($uploadFileInfo['id']);
            }
        } catch (\Exception $e) {
            exception_log('上传文件删除失败', $e);
            return false;
        }

        return true;
    }


    public function getFileData($file)
    {
        return $this->dao->getSearch(['show_src' => $file])->find();
    }


}